package tcp_udp;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Author: hu
 * Date: 2023/4/7 14:06
 */
public class TcpServer {
    public static void main(String[] args) throws IOException {
        // 1. 设置端口，让客户端找到
        ServerSocket server = new ServerSocket(2518);
        // 2. 监听客户端的连接
        Socket socket = server.accept();
        // 3. 文件输出 要文件流 接受数据 要字节流
        FileOutputStream fos = new FileOutputStream("地址");
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        // 4. 文件输出
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        // 5. 给予客户端回应
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println("接收完毕！");
        //关闭通道
        fos.close();
        bis.close();
        socket.close();
    }

    @Test
    public void tcpClinetTest() throws IOException {
        // 首先要有一个目标，向哪一个服务端发送消息
        InetSocketAddress serverIP = new InetSocketAddress("localhost", 2518);
        // 有了目标主机后，就可以建立连接
        Socket socket = new Socket();
        socket.connect(serverIP);
        // 已经连接上了，就可以发送数据，利用IO流
        OutputStream os = socket.getOutputStream();
        PrintStream ps = new PrintStream(os);	// 发文字消息用打印流更方便.
        ps.println("dbmgr hello this is a tcp server");
        ps.flush();
    }


}
